//
//  SNSViewController.m
//  HelloWorld
//
//  Created by MJiao on 15/6/24.
//  Copyright (c) 2015年 MJiao. All rights reserved.
//

#import "SNSViewController.h"

#import "MJRefresh.h"
#import "AFHTTPRequestOperationManager.h"
#import "KVNProgress.h"
#import "UIImageView+AFNetworking.h"

#import "MyFellow.h"
#import "MyFellowPageModel.h"
#import "FollowMe.h"
#import "FollowMePageModel.h"


#import "MyFellowingTableViewCell.h"
#import "MyFellowedTableViewCell.h"

#import "UserManager.h"
#import "CommonUtils.h"

#import "UserManager.h"
#import "SomeProfileIdentifierViewController.h"

enum {
    Following, //我关注的
    Followed //关注我的
} RequestType;

@interface SNSViewController ()
@property(nonatomic, assign) BOOL isFristOpen;


/** 用来显示的假数据 */
@property(strong, nonatomic) MyFellowPageModel *myFellowPageModel;
@property(strong, nonatomic) FollowMePageModel *followMePageModel;
@property(strong, nonatomic) MyFellow *didSelectedMyFellow;
@property(nonatomic) BOOL isWillReloadData;
@end


@implementation SNSViewController
- (IBAction)btnToLoginAction:(id)sender {
    [self performSegueWithIdentifier:@"toLoginIdentifier" sender:self];
}

- (void)viewWillAppear:(BOOL)animated {
    //取消上次选择中的被选择效果
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:NO];

    //检查当前用户是否已经登录
    if ([[UserManager shareUserManager] curUser].userId == -1) {
        if (!self.isFristOpen) {
            [self.noLoginTipView setHidden:NO];
            [self.tableView setHidden:YES];
        }
        self.isFristOpen = NO;
        return;
    }
    [self.noLoginTipView setHidden:YES];
    [self.tableView setHidden:NO];

    if (self.isWillReloadData) {
        // 马上进入刷新状态
        [self.tableView.header beginRefreshing];
        return;
    }
    if (self.isLoadedData) {
        return;
    }
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}

- (void)recvData:(NSNotification *)notification {
    self.isWillReloadData = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];


    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(recvData:)
                                                 name:@"SecVCPopped"
                                               object:nil];

    self.isFristOpen = YES;

    /**
    *  初始化数据集
    */
    if (!self.myFellowPageModel) {
        self.myFellowPageModel = [[MyFellowPageModel alloc] init];
        self.myFellowPageModel.dataArray = [[NSMutableArray alloc] init];
    }
    if (!self.followMePageModel) {
        self.followMePageModel = [[FollowMePageModel alloc] init];
        self.followMePageModel.dataArray = [[NSMutableArray alloc] init];
    }

    /**
    *  去掉TableView每个cell之间的默认分割线
    */
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    NSLog(@"[[UserManager shareUserManager]curUser] .userId:%ld",
            [[UserManager shareUserManager] curUser].userId);

    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

        NSString *stringURL = [NSString stringWithFormat:@"http://121.41.91.36:8888/api/uid/queryAttent?userId=%ld&currentPage=1", [[[UserManager shareUserManager] curUser] userId]];
        if(self.requestType == Followed){
            stringURL = [NSString stringWithFormat:@"http://121.41.91.36:8888/api/uid/queryBeAbout?userId=%ld&currentPage=1", [[[UserManager shareUserManager] curUser] userId]];
        }

        NSLog(@">>>%@",stringURL);
        [manager GET:stringURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

            self.isWillReloadData = NO;

            // NSLog(@"responseObject:%@",responseObject);
            // 结束刷新
            [self.tableView.header endRefreshing];

            self.isLoadedData = YES;



            MyFellowPageModel *tMyFellowPageModel = [[MyFellowPageModel alloc] init];

            NSMutableArray *dataArray = [[NSMutableArray alloc] init];
            tMyFellowPageModel.dataArray = dataArray;


            NSString *code = [responseObject objectForKey:@"code"];
            //登录失败
            if (code != nil && [code isEqualToString:@"00"]) {

                NSArray *result = [responseObject objectForKey:@"result"];
                [result enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                    NSString *fidImage = [obj objectForKey:@"fidImage"];
                    NSString *fidName = [obj objectForKey:@"fidName"];
                    NSInteger status = [[obj objectForKey:@"status"] integerValue];
                    NSInteger userId = [[obj objectForKey:@"fid"] integerValue];

                    MyFellow *myFellow = [[MyFellow alloc] init];
                    myFellow.fidImage = fidImage;
                    myFellow.fidName = fidName;
                    myFellow.status = status;
                    myFellow.userId = userId;

                    [dataArray addObject:myFellow];
                }];
                [self setMyFellowPageModel:tMyFellowPageModel];
            }
            [self.tableView reloadData];

        }    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            self.isWillReloadData = NO;

            NSLog(@"Error: %@", error);
            // 结束刷新
            [self.tableView.header endRefreshing];

            [KVNProgress showErrorWithStatus:@"网络异常,请稍后再试"];
        }];


        // 进入刷新状态后会自动调用这个block
    }];
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    self.tableView.header.autoChangeAlpha = YES;



    //检查当前用户是否已经登录
    if ([[UserManager shareUserManager] curUser].userId == -1) {
        [self performSegueWithIdentifier:@"toLoginIdentifier" sender:self];
        return;
    }


}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.didSelectedMyFellow = self.myFellowPageModel.dataArray[indexPath.row];

    [self performSegueWithIdentifier:@"SomeProfileSegueIdentifier" sender:self];
}

/**
*  拦截Segue
*/
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender {
    if ([sender isKindOfClass:[MyFellowingTableViewCell class]]) {
        // prevent segue from occurring
        return NO;
    }
    // by default perform the segue transition
    return YES;
}

/**
* 传递参数
*/
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"SomeProfileSegueIdentifier"]) {
        SomeProfileIdentifierViewController *destination = segue.destinationViewController;
        [destination setFid:self.didSelectedMyFellow.userId];
        if (self.requestType == Following) {
            [destination setFollowing:YES];
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.myFellowPageModel.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *ID = @"MyFellowingTableViewCell";
    MyFellowingTableViewCell *myFellowingTableViewCell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (myFellowingTableViewCell == nil) {
        myFellowingTableViewCell = [[MyFellowingTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }

    MyFellow *myFellow = [self.myFellowPageModel.dataArray objectAtIndex:[indexPath row]];

    if (myFellow.fidName == nil || ![myFellow.fidName isKindOfClass:[NSString class]] || myFellow.fidName.length == 0) {
        [myFellowingTableViewCell.lvNickName setText:@"昵称"];
    } else {
        [myFellowingTableViewCell.lvNickName setText:myFellow.fidName];
    }


    if (!(myFellow.fidImage == nil || ![myFellow.fidImage isKindOfClass:[NSString class]] || myFellow.fidImage.length == 0)) {

        NSURL *imageURL = [NSURL URLWithString:myFellow.fidImage];
        [myFellowingTableViewCell.ivAvatoar setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:@"defaultAvatar"]];
    }

    //圆角
    myFellowingTableViewCell.ivAvatoar.layer.masksToBounds = YES;
    myFellowingTableViewCell.ivAvatoar.layer.cornerRadius = 27.5;

    return myFellowingTableViewCell;
}

- (IBAction)switchRequestTypeAction:(id)sender {
    UISegmentedControl *segmentedControl = sender;
    NSInteger selectedSegment = segmentedControl.selectedSegmentIndex;
    [self.myFellowPageModel.dataArray removeAllObjects];
    if (selectedSegment == 0) {
        self.requestType = Following;
    }
    else {
        self.requestType = Followed;
    }
    [self.tableView reloadData];
    // 进入刷新状态
    [self.tableView.header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
